package com.atguigu.flink.cep;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.List;
import java.util.Map;

/**

 */
public class Demo2_Time
{
    public static void main(String[] args) {
        
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy.<WaterSensor>forMonotonousTimestamps()
            .withTimestampAssigner( (e, r) -> e.getTs());


        SingleOutputStreamOperator<WaterSensor> ds = env
            .readTextFile("data/cep.txt")
            .map(new WaterSensorMapFunction())
            .assignTimestampsAndWatermarks(watermarkStrategy);



        Pattern<WaterSensor, WaterSensor> pattern = Pattern.<WaterSensor>begin("匹配s1")
            .where(new SimpleCondition<WaterSensor>()
            {
                // 定义匹配条件
                @Override
                public boolean filter(WaterSensor value) throws Exception {
                    return "s1".equals(value.getId());
                }
            })
            // 定义的where条件，应用两次去匹配
            //.times(2)
            // 定义的where条件，应用2次 或 3次
            //.times(2,3)
            //定义的where条件，应用2次 或 N(>2)次。 危险，1001这条要一直缓存，不断和后续对数据进行匹配。会和终止条件配合
            //.timesOrMore(2)
            // 定义的where条件，应用1次 或 N(>1)次。
            .oneOrMore()
            //到....为止
            .until(new SimpleCondition<WaterSensor>()
            {
                @Override
                public boolean filter(WaterSensor value) throws Exception {
                    return "s2".equals(value.getId());
                }
            })

           ;


        PatternStream<WaterSensor> patternStream = CEP.pattern(ds, pattern);

        patternStream.select(new PatternSelectFunction<WaterSensor, String>()
        {
            @Override
            public String select(Map<String, List<WaterSensor>> map) throws Exception {
                return map.toString();
            }
        }).print();


        try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
        
    }
}
